import { createGlobalState, extendRef, useIntervalFn } from '@peng_kai/kit/libs/vueuse';
import { icStorage } from '~/components-business/auth/helpers';

export const useAuthed = createGlobalState(() => {
  const isAuthed = ref(hasToken());
  isAuthed && icStorage.set('');

  useIntervalFn(() => {
    if (document.visibilityState === 'visible') {
      isAuthed.value = hasToken();
    }
  }, 1000, { immediate: true });

  // 授权状态变化时，刷新所有查询
  watch(isAuthed, (isAuthed) => {
    if (isAuthed) {
      appValues.refreshRoute?.();
      globalPopups.sign.close();
      queryClient.invalidateQueries();
      icStorage.set('');
      console.log('登陆成功');
    }
    else {
      // getAppRouter().push({ name: RN.INDEX });
      // antdMessage.destroy();
      // antdNotification.destroy();
      // queryClient.removeQueries();
      location.reload();
    }
  }, { flush: 'pre' });

  /** 等待授权状态变为已授权 */
  function suspense() {
    const resolvers = Promise.withResolvers();

    const stop = watch(isAuthed, (value) => {
      if (value) {
        resolvers.resolve(true);
        setTimeout(stop);
      }
    }, { immediate: true });

    return resolvers.promise;
  }

  return extendRef(isAuthed, { suspense });
});
